package bean.dao;

import hbt.HibernateUtil;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import bean.Proveedor;

public class HibernateProveedorDAO {
	
	private static HibernateProveedorDAO instancia = null;
	private static SessionFactory sf = null;

	public static HibernateProveedorDAO getInstancia(){
		if(instancia == null){
			sf = HibernateUtil.getSessionFactory();
			instancia = new HibernateProveedorDAO();
		} 
		return instancia;
	}
	
	public void grabarProveedor(Proveedor nuevoProveedor){
		Session session = sf.openSession();
		session.beginTransaction();
		session.persist(nuevoProveedor);
		session.flush();
		session.getTransaction().commit();
		session.close();
	}
	
	public Proveedor buscarProveedorPorCUIT (String cuitBuscado) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		String hql = "from Proveedor p where p.cuit = :cuit";
		Query query = session.createQuery(hql);
		query.setParameter("cuit", cuitBuscado);
		Proveedor p = (Proveedor) query.uniqueResult();
		session.close();		
		return p;
	}

	public boolean borrarProveedor(String numeroCUIT) {
		if (buscarProveedorPorCUIT(numeroCUIT) == null)
			return false;
		
		else {
			Session session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			
			session.delete(buscarProveedorPorCUIT(numeroCUIT));
			
			session.flush();
			session.getTransaction().commit();
			session.close();
			return true;
		}
	}

	public void actualizarDatosProveedor(Proveedor proveedorAModificar) {
		// TODO Auto-generated method stub
		Session sesion = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = sesion.beginTransaction();
		String hql = "Update Proveedor p set p.razonSocial = :nuevaRazonSocial, p.cuit = :nuevoCUIT," +
				"p.telefono = :nuevoTelefono where p.id = :id ";
		
		Query query = sesion.createQuery(hql);
		query.setParameter("nuevaRazonSocial", proveedorAModificar.getRazonSocial());
		query.setParameter("nuevoCUIT", proveedorAModificar.getCuit());
		query.setParameter("nuevoTelefono", proveedorAModificar.getTelefono());
		query.setParameter("id", proveedorAModificar.getId());
		query.executeUpdate();
		tx.commit();
		sesion.close();
	}
}